package com.lisn.fileuploadlib;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.UriUtils;
import com.lisn.fragmentationupload.upload.UploadManager;
import com.lisn.fragmentationupload.upload.UploadTask;
import com.lisn.fragmentationupload.upload.UploadTaskListener;
import com.lisn.fragmentationupload.utils.MLog;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();

    private ProgressBar mProgressBar;
    private Button mButton;
    private Button mButtonPause;
    private Button mButtonCancel;
    private Button mButtonResume;
    private TextView mTvStatus;

    private static String URL_Test_ID = "url_test";

    private String url_test = "http://172.22.44.9:8080/uploadsg";

    private String filePath;
    private UploadManager uploadManager;
    private TextView tv_path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uploadManager = UploadManager.getInstance();
        initView();
    }

    private void initView() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(this);

        mButtonPause = (Button) findViewById(R.id.buttonpause);
        mButtonPause.setOnClickListener(this);

        mButtonCancel = (Button) findViewById(R.id.buttoncancel);
        mButtonCancel.setOnClickListener(this);

        mButtonResume = (Button) findViewById(R.id.buttonresume);
        mButtonResume.setOnClickListener(this);

        mTvStatus = (TextView) findViewById(R.id.tv_status);
        tv_path = (TextView) findViewById(R.id.tv_path);

        findViewById(R.id.bt_chooseFile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseFile();
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (mButton == v) {
            // download360();
            test();
        } else if (mButtonPause == v) {
            uploadManager.pause(URL_Test_ID);
        } else if (mButtonResume == v) {
            uploadManager.resume(URL_Test_ID);
        }
    }

    public void test() {
        MLog.e(TAG, "test: ");

        if (TextUtils.isEmpty(this.filePath)) {
            Toast.makeText(this, "请先选择文件路径", Toast.LENGTH_SHORT).show();
            return;
        }
        final int chunk = 1;
        UploadTaskListener uploadTaskListener = new UploadTaskListener() {
            @Override
            public void onUploading(UploadTask uploadTask, String percent) {
                MLog.e(TAG, "onUploading: percent = " + percent);
                if (uploadTask.getId().equals(URL_Test_ID)) {
                    mProgressBar.setProgress(Integer.parseInt(percent));
                    mTvStatus.setText("正在下载..." + percent + "%");
                } else {
                    mProgressBar.setProgress(Integer.parseInt(percent));
                    mTvStatus.setText("正在上传..." + percent + "%");
                }
            }

            @Override
            public void onUploadSuccess(UploadTask uploadTask, String filePath) {
                MLog.e(TAG, "onUploadSuccess: " + filePath);
                if (uploadTask.getId().equals(URL_Test_ID)) {
                    mTvStatus.setText("上传完成 path：" + filePath);
                } else {
                    mTvStatus.setText("上传完成 path：" + filePath);
                }
            }

            @Override
            public void onError(UploadTask uploadTask, int errorCode) {
                MLog.e(TAG, "onError: " + errorCode);
                if (uploadTask.getId().equals(URL_Test_ID)) {
                    mTvStatus.setText("上传失败=" + errorCode);
                } else {
                    mTvStatus.setText("上传失败errorCode=" + errorCode);
                }
            }

            @Override
            public void onPause(UploadTask uploadTask) {
                MLog.e(TAG, "onPause: ");
                if (uploadTask.getId().equals(URL_Test_ID)) {
                    mTvStatus.setText("上传暂停！");
                } else {
                    mTvStatus.setText("上传暂停！");
                }
            }
        };
        UploadTask task = new UploadTask.Builder()
                .setId(URL_Test_ID)
                .setUrl(url_test)
                .setChunk(chunk)
                .setFileName(new File(filePath).getName())
                .setFilePath(filePath)
                .setListener(uploadTaskListener)
                .build();
        uploadManager.addUploadTask(task);
    }

    public void chooseFile() {
        //所需权限
        String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
        //如果没有权限
        if (ActivityCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, permissions[1]) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, permissions, 1);//申请权限
        }

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); //使用系统的文件选择器
        intent.setType("*/*"); //所有类型的文件
        intent.addCategory(Intent.CATEGORY_OPENABLE); //期望获取的数据可以作为一个File打开
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            Log.e(TAG, "onActivityResult: uri = " + uri);
            this.filePath = UriUtils.uri2File(uri).getPath();
            Log.e(TAG, "onActivityResult: path = " + filePath);

            tv_path.setText(filePath);
        }
    }

}